<script setup lang="ts">
import { ref, shallowRef } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from 'element-plus';
import { isLoggedIn, getUserInfo, removeToken, removeUserInfo, removeUserRole, clearRememberMe } from "@/utils/auth";
import { userApi } from "@/api/customer";
import { useThemeStore } from "@/store";
import { 
  Search,
  ArrowDown,
  User,
  Tickets,
  Location,
  Star,
  Clock,
  SwitchButton,
  ShoppingCart,
  Sunny,
  Moon
} from '@element-plus/icons-vue';

const router = useRouter();
const themeStore = useThemeStore();
const user = shallowRef(getUserInfo());
const loggedIn = ref(isLoggedIn());
const searchKeyword = ref("");
const cartCount = ref(0); // 购物车数量，实际应用中应该从API获取

// 切换主题
const toggleTheme = () => {
  themeStore.toggleCustomerTheme();
  
  // 简单的用户反馈
  const themeText = themeStore.isDark ? '暗色模式' : '亮色模式';
  ElMessage({
    message: `已切换到${themeText}`,
    type: 'success',
    duration: 1500,
    showClose: false
  });
};

// 退出登录
const logout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const loading = ElMessage({
      message: '正在退出登录...',
      type: 'info',
      duration: 0 // 不自动关闭
    });

    try {
      // 调用退出登录API，设置较短的超时时间
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), 5000); // 5秒超时
      
      await userApi.logout();
      clearTimeout(timeoutId);
      console.log('退出登录API调用成功');
    } catch (error: any) {
      console.error('退出登录API调用失败:', error);
      
      // 检查是否是超时或网络错误
      if (error.name === 'AbortError' || error.code === 'ECONNABORTED') {
        console.warn('退出登录API超时，但继续清除本地存储');
      } else if (error.message?.includes('timeout') || error.message?.includes('Network Error')) {
        console.warn('网络超时或连接错误，但继续清除本地存储');
      }
      
      // 即使API调用失败，也继续清除本地存储
    } finally {
      loading.close(); // 关闭loading提示
      
      // 彻底清除所有认证信息，包括记住的登录信息
      removeToken();
      removeUserInfo();
      removeUserRole();
      clearRememberMe(); // 添加这行来清除记住的登录信息
      
      // 更新本地状态
      user.value = null;
      loggedIn.value = false;
      
      ElMessage.success('已退出登录');
      router.push('/customer/login');
    }
  }).catch(() => {
    // 用户取消操作，不做任何处理
  });
};

// 跳转到搜索页
const goToSearch = (keyword: string = "") => {
  if (keyword.trim()) {
    router.push(`/customer/search?keyword=${encodeURIComponent(keyword.trim())}`);
  }
};

// 跳转到登录页
const goToLogin = () => {
  router.push("/customer/login");
};

// 跳转到用户中心
const goToProfile = () => {
  router.push("/customer/profile");
};

// 跳转到购物车
const goToCart = () => {
  router.push("/customer/cart");
};

// 跳转到订单页
const goToOrders = () => {
  router.push("/customer/orders");
};

// 跳转到首页
const goToHome = () => {
  router.push("/customer");
};

// 跳转到商家列表
const goToStores = () => {
  router.push("/customer/stores");
};

defineExpose({
  goToSearch,
  goToLogin,
  goToProfile,
  goToCart,
  goToOrders,
  goToHome,
  goToStores
});
</script>

<template>
  <div class="customer-layout">
    <!-- 顶部导航栏 -->
    <header class="customer-header">
      <div class="header-content">
        <div class="logo-section" @click="goToHome">
          <img src="/logo.png" alt="饱了么" class="logo" />
          <h1 class="site-name">饱了么</h1>
        </div>
        
        <div class="nav-section">
          <el-button link @click="goToHome">首页</el-button>
          <el-button link @click="goToStores">商家列表</el-button>
        </div>
        
        <div class="search-section">
          <el-input 
            placeholder="搜索商家、美食..." 
            class="search-input"
            v-model="searchKeyword"
            @keyup.enter="goToSearch(searchKeyword)"
          >
            <template #suffix>
              <el-icon @click="goToSearch(searchKeyword)"><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <div class="user-section">
          <!-- 主题切换按钮 -->
          <el-button 
            link 
            @click="toggleTheme"
            :title="themeStore.isDark ? '切换到亮色模式' : '切换到暗色模式'"
            class="theme-toggle"
          >
            <el-icon>
              <Sunny v-if="themeStore.isDark" />
              <Moon v-else />
            </el-icon>
          </el-button>
          
          <template v-if="loggedIn">
            <el-dropdown trigger="click">
              <span class="user-dropdown-link">
                {{ user?.username || '用户' }}
                <el-icon><ArrowDown /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="goToProfile">
                    <el-icon><User /></el-icon>个人中心
                  </el-dropdown-item>
                  <el-dropdown-item @click="goToOrders">
                    <el-icon><Tickets /></el-icon>我的订单
                  </el-dropdown-item>
                  <el-dropdown-item @click="router.push('/customer/addresses')">
                    <el-icon><Location /></el-icon>我的地址
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-dropdown placement="right-start" trigger="hover">
                      <div style="display: flex; align-items: center;">
                        <el-icon><Star /></el-icon>我的收藏
                      </div>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item @click="router.push('/customer/favorites/stores')">
                            收藏的店铺
                          </el-dropdown-item>
                          <el-dropdown-item @click="router.push('/customer/favorites/foods')">
                            收藏的商品
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </el-dropdown-item>
                  <el-dropdown-item @click="router.push('/customer/history')">
                    <el-icon><Clock /></el-icon>浏览历史
                  </el-dropdown-item>
                  <el-dropdown-item divided @click="logout">
                    <el-icon><SwitchButton /></el-icon>退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
          <template v-else>
            <el-button link @click="goToLogin">登录/注册</el-button>
          </template>
          <el-button link @click="goToCart">
            <el-badge :value="cartCount" :hidden="cartCount === 0">
              <el-icon><ShoppingCart /></el-icon>购物车
            </el-badge>
          </el-button>
          <el-button link @click="goToOrders">
            <el-icon><Tickets /></el-icon>订单
          </el-button>
        </div>
      </div>
    </header>

    <!-- 主要内容区 -->
    <main class="customer-main">
      <!-- 插槽，用于放置各页面的内容 -->
      <slot></slot>
    </main>

    <!-- 页脚 -->
    <footer class="customer-footer">
      <div class="footer-content">
        <div class="footer-section">
          <h3>关于我们</h3>
          <p>饱了么是一个专注于校园场景的外卖下单平台，致力于为师生提供便捷的美食服务。</p>
        </div>
        <div class="footer-section">
          <h3>联系我们</h3>
          <p>邮箱: xxxxxxx</p>
          <p>电话: xxxxxxxxx</p>
        </div>
        <div class="footer-section">
          <h3>关注我们</h3>
          <div class="social-links">
            
            <a href="#">微信：xxxxxx</a>
          
          </div>
        </div>
      </div>
      <div class="copyright">
        © 2025 饱了么 版权所有
      </div>
    </footer>
  </div>
</template>

<style scoped>
.customer-layout {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

/* 顶部导航栏样式 */
.customer-header {
  background-color: #ffe082;
  padding: 15px 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 10;
  transition: background-color 0.3s ease, box-shadow 0.3s ease;
}

.header-content {
  max-width: 2100px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
}

.logo-section {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.logo {
  width: 40px;
  height: 40px;
  margin-right: 10px;
}

.site-name {
  font-size: 24px;
  color: #8b4513;
  margin: 0;
  transition: color 0.3s ease;
}

.nav-section {
  display: flex;
  align-items: center;
  gap: 10px;
}

.nav-section .el-button {
  font-size: 16px;
  color: #8b4513;
  font-weight: 500;
  transition: color 0.3s ease;
}

.nav-section .el-button:hover {
  color: #ff6b6b;
}

.search-section {
  flex: 1;
  max-width: 500px;
  margin: 0 20px;
}

.search-input {
  width: 100%;
}

.user-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.theme-toggle {
  padding: 8px;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.theme-toggle:hover {
  background-color: rgba(255, 107, 107, 0.1);
  transform: scale(1.1);
}

.user-dropdown-link {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #8b4513;
  transition: color 0.3s ease;
}

.user-dropdown-link .el-icon {
  margin-left: 4px;
}

/* 主要内容区样式 */
.customer-main {
  flex: 1;
  padding: 20px;
  max-width: 2100px;
  margin: 0 auto;
  width: 100%;
}

/* 页脚样式 */
.customer-footer {
  background-color: #fff3cd;
  padding: 40px 0 20px;
  margin-top: 40px;
  transition: background-color 0.3s ease;
}

.footer-content {
  max-width: 2100px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
}

.footer-section {
  max-width: 300px;
}

.footer-section h3 {
  font-size: 18px;
  color: #8b4513;
  margin-bottom: 15px;
  transition: color 0.3s ease;
}

.footer-section p {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
  transition: color 0.3s ease;
}

.social-links {
  display: flex;
  gap: 15px;
}

.social-links a {
  color: #8b4513;
  text-decoration: none;
  transition: color 0.3s ease;
}

.copyright {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ffe082;
  font-size: 14px;
  color: #999;
  transition: color 0.3s ease, border-color 0.3s ease;
}

/* 暗色主题支持 */
body.customer-dark-theme .customer-header {
  background-color: #3a3a3a;
  border-bottom: 1px solid #555;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}

body.customer-dark-theme .site-name {
  color: #ffa726;
}

body.customer-dark-theme .nav-section .el-button {
  color: #f0f0f0;
}

body.customer-dark-theme .nav-section .el-button:hover {
  color: #ffa726;
}

body.customer-dark-theme .user-dropdown-link {
  color: #f0f0f0;
}

body.customer-dark-theme .theme-toggle:hover {
  background-color: rgba(255, 167, 38, 0.1);
  transform: scale(1.1);
}

body.customer-dark-theme .customer-footer {
  background-color: #3a3a3a;
  border-top: 1px solid #555;
}

body.customer-dark-theme .footer-section h3 {
  color: #ffa726;
}

body.customer-dark-theme .footer-section p {
  color: #c0c0c0;
}

body.customer-dark-theme .social-links a {
  color: #ffa726;
}

body.customer-dark-theme .copyright {
  border-top: 1px solid #555;
  color: #aaa;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 15px;
  }
  
  .search-section {
    margin: 0;
    max-width: 100%;
  }
  
  .user-section {
    gap: 10px;
  }
  
  .footer-content {
    flex-direction: column;
    gap: 30px;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 10px;
  }
  
  .search-section {
    width: 100%;
    max-width: none;
    margin: 10px 0;
  }
  
  .footer-content {
    flex-direction: column;
    gap: 20px;
  }
}
</style>
